﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos;
using Work.ErrorCode;

namespace Work.API.Controllers
{
    /// <summary>
    /// API控制器,用户登录
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMediator mediator;

        public UserController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [HttpPost]
        public async Task<ApiResult<LoginDTO>> Login([FromBody] LoginCommand request)
        {
            try
            {
                var query = new LoginCommand
                {
                    Username = request.Username,
                    Password = request.Password
                };

                return await mediator.Send(query);
            }
            catch (Exception ex)
            {
                return new ApiResult<LoginDTO>
                {
                    Code = ApiEnum.失败,
                    Message = $"登录失败：{ex.Message}",
                    Data = new LoginDTO
                    {
                        Success = false,
                        Message = ex.Message
                    }
                };
            }
        }
    }
}
